package com.lab.schemeurl;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.WebView;

import com.lab.logtrack.AppLog;
import com.lab.schemeurl.constant.Host;
import com.lab.schemeurl.constant.Scheme;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by ak
 * 处理SchemeUrl
 */
public class SchemeUrlDispatcher {

    public static final String PARAM_EVENT = "evt";

    private ISchemeUrlHandler mSchemeUrlHandler;

    private Map<String, WeakReference<WebView>> mSchemeUrlEventCallback = new HashMap<String, WeakReference<WebView>>();

    private Set<Scheme> mPermitSchemes = new HashSet<Scheme>();

    public SchemeUrlDispatcher(ISchemeUrlHandler schemeUrlHandler) {
        this.mSchemeUrlHandler = schemeUrlHandler;
        addPermitScheme(Scheme.CUITRIP);
        addPermitScheme(Scheme.HTTP);
    }

    public void addPermitScheme(Scheme scheme) {
        if (null != scheme) {
            mPermitSchemes.add(scheme);
        }
    }

    public void removePermitScheme(Scheme scheme) {
        if (null != scheme) {
            mPermitSchemes.remove(scheme);
        }
    }

    public boolean isSchemePermitted(Scheme scheme) {
        if (null != scheme) {
            return mPermitSchemes.contains(scheme);
        }
        return false;
    }

    public final boolean dispatch(Uri uri) {
        return dispatch(uri, null);
    }

    public final boolean dispatch(Uri uri, WebView webView) {
        return dispatch(null, uri, webView);
    }

    public final boolean dispatch(Context context, Uri uri, WebView webView) {
        if (null != uri) {
            Scheme scheme = Scheme.getSchemeByName(uri.getScheme());
            if (!isSchemePermitted(scheme)) {
                return false;
            }
            // Http Scheme
            if (scheme.equals(Scheme.HTTP)) {
                if (null != mSchemeUrlHandler) {
                    String eventName = uri.getQueryParameter(PARAM_EVENT);
                    registerEventCallback(eventName, webView);
                    return mSchemeUrlHandler.onSchemeUrlHandle(context, uri, scheme, null);
                }
            }
            // CuiTrip Scheme
            else if (scheme.equals(Scheme.CUITRIP)) {
                Host host = Host.getHostByName(uri.getHost().trim());
                if (null != host && null != mSchemeUrlHandler) {
                    String eventName = uri.getQueryParameter(PARAM_EVENT);
                    registerEventCallback(eventName, webView);
                    return mSchemeUrlHandler.onSchemeUrlHandle(context, uri, scheme, host);
                }
            }
        }
        return false;
    }

    public final boolean handleEventResult(String event, String result) {
        if (!TextUtils.isEmpty(event) && !TextUtils.isEmpty(result)) {
            WeakReference<WebView> reference = mSchemeUrlEventCallback.get(event);
            if (null != reference) {
                WebView webView = reference.get();
                if (null != webView) {
                    // 回调webview时,可能会因webview当前已销毁而导致异常
                    try {
                        webView.loadUrl(String.format("javascript:apiJs.evtResult('%s','%s')", result, event));
                    } catch (Exception e) {
                        AppLog.d(e.getMessage());
                    }
                    return true;
                }
            }
        }
        return false;
    }



    private void registerEventCallback(String event, WebView callback) {
        if (TextUtils.isEmpty(event) || null == callback) return;
        mSchemeUrlEventCallback.put(event, new WeakReference<WebView>(callback));
    }

    public interface ISchemeUrlHandler {
        public abstract boolean onSchemeUrlHandle(Context context, Uri uri, Scheme scheme, Host host);
    }

}